<template>
  <div style="border: 1px solid #ccc">
    <Toolbar
        style="border-bottom: 1px solid #ccc"
        :editor="editorRef"
        :defaultConfig="toolbarConfig"

    />
    <Editor
        style="height: 500px; overflow-y: hidden;"
        v-model="valueHtml"
        :defaultConfig="editorConfig"

        @onCreated="handleCreated"
    />
  </div>
</template>

<script setup lang="ts">
import '@wangeditor/editor/dist/css/style.css' // 引入 css
import { onBeforeUnmount, onMounted, ref, shallowRef, watchEffect, watch, defineProps, defineEmits } from 'vue'
import {Editor, Toolbar} from '@wangeditor/editor-for-vue'

// 定义 props
const props = defineProps({
  modelValue: {
    type: String,
    default: "",
  }
})

// 定义 emits
const emits = defineEmits<{
  (e: "update:modelValue", value: string): void
}>()

// 内容 HTML
const valueHtml = ref<string>('<p>hello</p>')

// 模拟 ajax 异步获取内容
onMounted(() => {
  // setTimeout(() => {
    // valueHtml.value = '<p>asd</p>'
  // }, 1500)
})

const baseUrl = import.meta.env.VITE_BASE_URL
const toolbarConfig={}
const editorConfig={
  MENU_CONF:{
    uploadImage:{
      server:baseUrl + "/files/upload",
      fieldName:"file",
      customInsert(res:any,insertFn:any){
        console.log(res.data)
        insertFn(res.data)
      },
    },
  }
}
// 编辑器实例，必须用 shallowRef
const editorRef = shallowRef<Editor>()

// 监听 props 更新 valueHtml
watchEffect(() => {
  valueHtml.value = props.modelValue
})

// 监听 valueHtml 变化，触发更新事件
watch(valueHtml, (newHtml) => {
  emits("update:modelValue", newHtml)
})

// 组件销毁时，也及时销毁编辑器
onBeforeUnmount(() => {
  const editor = editorRef.value
  if (editor == null) return
  editor.destroy()
})

// 编辑器创建时，保存 editor 实例
const handleCreated = (editor: Editor) => {
  editorRef.value = editor // 记录 editor 实例，重要！
}
</script>